package dk.oldommer.bjw.model.user;


import java.util.*;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.junit.*;

import dk.oldommer.bjw.HibernateUtil;

/**
 * @author SML
 *
 */
public class UserFacadeImpl implements UserFacade {

	@Override
	public User create(UserValues userValues) throws FacadeException {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		User user = new User(userValues);
		session.save(user);
		session.getTransaction().commit();
		return user;
	}

	@Override
	public List<User> findAll() throws FacadeException {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<User> users = (List<User>) session.createQuery("from User").list();
		session.getTransaction().commit();
		return users;
	}



	@Override
	public User get(Long id) throws FacadeException {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		User user = (User) session.load(User.class, id);
		
		// Make sure that proxy object is initialized from database row
		Hibernate.initialize(user);
		session.getTransaction().commit();
		return user;
	}

	@Override
	public void save(Long id, UserValues userValues) throws FacadeException {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		User user = (User) session.load(User.class, id);
		user.setValues(userValues);
		session.getTransaction().commit();
		
	}

}
